package com.bss.framework;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bss.command.PatientCommand;

public class ImageController {

	public void click(HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		InputStream iis = request.getInputStream();

		ByteArrayOutputStream bos = new ByteArrayOutputStream(1024 * 8);

		byte data[] = new byte[1024];
		while (true) {
			int n = iis.read(data);
			if (n <= 0) {
				break;
			}
			bos.write(data, 0, n);
		}

		PatientCommand.setImage(bos.toByteArray());
		PatientCommand.setClicked(true);

		response.getWriter().write(
				"bss/images/clicked?id=" + new Date().getTime());
	}

	public void clicked(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			response.setContentType("image/jpeg");
			response.setContentLength(PatientCommand.getImage().length);
			response.getOutputStream().write(PatientCommand.getImage());
		} catch (Exception e) {
			response.setStatus(HttpServletResponse.SC_NO_CONTENT);
		}
	}

	public void saved(HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		int patientId = Integer.parseInt(request.getParameter("id").toString());

		InputStream img = PatientCommand.downloadImage(patientId);
		int size = 0;
		byte[] bytearray = new byte[1024];

		ByteArrayOutputStream bos = new ByteArrayOutputStream(1024 * 8);

		response.setContentType("image/jpeg");
		while ((size = img.read(bytearray)) != -1) {
			response.getOutputStream().write(bytearray, 0, size);
			bos.write(bytearray, 0, size);
		}
		PatientCommand.setImage(bos.toByteArray());

	}

}
